<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Goods extends Model
{
    use SoftDeletes;
    protected $table = 'goods';
    protected $fillable=[ 'name', 'slug' , 'goods_type_id' , 'brand_id' , 'bn' , 'summary' ,'spes_desc',
        'weight' , 'unit' , 'marketable' , 'is_recommend' , 'is_hot', 'content' , 'post_thumb' , 'price' , 'costprice'
        , 'market_price','params', 'stock', 'meta_title', 'meta_keywords', 'meta_description'
    ];

    protected $appends = ['params_text','attributes_text','category_id','spec_num'];

    public function manyParams()
    {
        return $this->belongsToMany(GoodsParames::class,'goods_type_params','type_id','params_id');
    }

    public function manyAttributes()
    {
        return $this->belongsToMany(GoodsAttributes::class,'goods_type_attributes','type_id','attribute_id');
    }

    public function manyImages()
    {
        return $this->belongsToMany(Images::class,'goods_images','goods_id','image_id');
    }
    public function manyCategory()
    {
        return $this->belongsToMany(Category::class,'goods_category','goods_id','category_id');
    }

    public function goodsItems()
    {
        return $this->hasMany(GoodsItems::class,'goods_id','id');
    }

    public function getParamsTextAttribute()
    {
        return unserialize($this->params);
    }

    public function getAttributesTextAttribute()
    {
        return unserialize($this->spes_desc);
    }

    public function getCategoryIdAttribute()
    {
        $checkArr = [];
        foreach ($this->manyCategory as $key =>$val)
        {
            $checkArr[] = $val->id;
        }
        return $checkArr;
    }
    public function getSpecNumAttribute()
    {
        return count($this->goodsItems);
    }
}
